﻿using CWCS.Common;
using CWCS.Core.Library;
using CWCS.Core.Library.SocketManager;
using CWCS.DataAccess;
using LOG;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CWCS.BLL;

namespace CWCS.UI
{
    public partial class FrmOCV : Form
    {
        #region 自动关闭弹出框
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        public const int WM_CLOSE = 0x10;

        private void StartKiller()
        {
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 500;
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            KillMessageBox();
            //停止Timer   
            ((System.Windows.Forms.Timer)sender).Stop();
        }

        private void KillMessageBox()
        {
            //依MessageBox的標題,找出MessageBox的視窗   
            IntPtr ptr = FindWindow(null, " ");
            if (ptr != IntPtr.Zero)
            {
                //找到則關閉MessageBox視窗   
                PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }
        #endregion

        private delegate void RichBoxCallBack(RichTextBox rb, string msg);
        public object ob = new object();
        private string WCSIP = System.Configuration.ConfigurationSettings.AppSettings["WCSIP"].ToString();
        private string OCV1PORT = System.Configuration.ConfigurationSettings.AppSettings["OCV1PORT"].ToString();
        private string OCV2PORT = System.Configuration.ConfigurationSettings.AppSettings["OCV2PORT"].ToString();
        private string OCV3PORT = System.Configuration.ConfigurationSettings.AppSettings["OCV3PORT"].ToString();
        private string DCIR1PORT = System.Configuration.ConfigurationSettings.AppSettings["DCIR1PORT"].ToString();
        private string DCIR2PORT = System.Configuration.ConfigurationSettings.AppSettings["DCIR2PORT"].ToString();


        private CRLSocketServer ocv1server = new CRLSocketServer();
        private CRLSocketServer ocv2server = new CRLSocketServer();
        private CRLSocketServer ocv3server = new CRLSocketServer();
        private CRLSocketServer dcir1server = new CRLSocketServer();
        private CRLSocketServer dcir2server = new CRLSocketServer();


        public Log log = new Log("OCV与DCIR", ".\\OCV与DCIR\\OCV与DCIR日志\\");
        public DALDATA dal = new DALDATA();
        public FrmOCV()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void FormBSD_Load(object sender, EventArgs e)
        {
            ocv1server.Notify += new CRLSocketServer.NotifyCommandHander_SS(ocv1_Notify);
            ocv1server.ServerStart(WCSIP, int.Parse(OCV1PORT));
            System.Threading.Thread.Sleep(100);

            ocv2server.Notify += new CRLSocketServer.NotifyCommandHander_SS(ocv2_Notify);
            ocv2server.ServerStart(WCSIP, int.Parse(OCV2PORT));
            System.Threading.Thread.Sleep(100);

            ocv3server.Notify += new CRLSocketServer.NotifyCommandHander_SS(ocv3_Notify);
            ocv3server.ServerStart(WCSIP, int.Parse(OCV3PORT));
            System.Threading.Thread.Sleep(100);

            dcir1server.Notify += new CRLSocketServer.NotifyCommandHander_SS(dcir1_Notify);
            dcir1server.ServerStart(WCSIP, int.Parse(DCIR1PORT));
            System.Threading.Thread.Sleep(100);

            dcir2server.Notify += new CRLSocketServer.NotifyCommandHander_SS(dcir2_Notify);
            dcir2server.ServerStart(WCSIP, int.Parse(DCIR2PORT));
            System.Threading.Thread.Sleep(100);
;
        }
        private void ocv1_Notify(string Command, object mesg)
        {
            bool b_Flag = false;
            string msg = "";
            try
            {
                if (Command == "Heart")
                {
                    OCV1.BackColor = OCV1.BackColor == Color.Lime ? Color.LimeGreen : Color.Lime;
                    OCV1.Text = "OCV1号机:已连接";
                }
                else if (Command == "Connect")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    OCV1.BackColor = Color.Lime;
                }
                else if (Command == "Break")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    OCV1.BackColor = Color.RosyBrown;
                }
                else if (Command == "Listen")
                {
                    WriteLog(rtb_conn, " OCV1号机开启监听！" + mesg);
                    OCV1.BackColor = Color.Orange;
                    OCV1.Text = "OCV1号机:监听中";
                }
                else if (Command == "Listen1")
                {
                    OCV1.BackColor = Color.Orange;
                    OCV1.Text = "OCV1号机:监听中";
                }
                else
                {
                    CommonHelper helper = new CommonHelper();

                    object obj = helper.Deserialize(mesg.ToString(), typeof(EuipmentInfo), ref b_Flag, ref msg);
                    if (obj is EuipmentInfo)
                    {
                        string typecode = string.Empty;

                        EuipmentInfo euipmentInfo = obj as EuipmentInfo;
                        typecode = euipmentInfo.Msg_Method;
                        List<ResultParam> resultParams = new List<ResultParam>();
                        ResultParam resultParam = new ResultParam();
                        if (typecode == "EuipmentStatus")
                        {
                            foreach (EquipmentParam equipmentParam in euipmentInfo.Msg_Params)
                            {
                                //更新设备状态 
                                resultParam.DeviceCode = equipmentParam.DeviceCode;
                                resultParam.DeviceType = equipmentParam.DeviceType;
                                resultParam.Code = "0";
                                resultParams.Add(resultParam);
                                if (int.Parse(equipmentParam.AlarmCode) > 0)
                                {
                                    WriteLog(rtb_msg, resultParam.DeviceType + resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));
                                    QueueSpeech.AddQueue(resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));

                                }
                            }
                            byte[] byt = new byte[1000];
                            string sendInfo = JsonConvert.SerializeObject(resultParams);
                            byte[] infotemp = System.Text.ASCIIEncoding.Default.GetBytes(sendInfo);
                            Array.Copy(infotemp, 0, byt, 0, infotemp.Length);
                            ocv1server.SendMessage(byt);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(rtb_msg, ex.Message + ex.StackTrace + ex.Source + ex.TargetSite);
            }
        }

        private void ocv2_Notify(string Command, object mesg)
        {
            bool b_Flag = false;
            string msg = "";
            try
            {
                if (Command == "Heart")
                {
                    OCV2.BackColor = OCV2.BackColor == Color.Lime ? Color.LimeGreen : Color.Lime;
                    OCV2.Text = "OCV2号机:已连接";
                }
                else if (Command == "Connect")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    OCV2.BackColor = Color.Lime;
                }
                else if (Command == "Break")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    OCV2.BackColor = Color.RosyBrown;
                }
                else if (Command == "Listen")
                {
                    WriteLog(rtb_conn, " OCV2号机开启监听！" + mesg);
                    OCV2.BackColor = Color.Orange;
                    OCV2.Text = "OCV2号机:监听中";
                }
                else if (Command == "Listen1")
                {
                    OCV2.BackColor = Color.Orange;
                    OCV2.Text = "OCV2号机:监听中";
                }
                else
                {
                    CommonHelper helper = new CommonHelper();

                    object obj = helper.Deserialize(mesg.ToString(), typeof(EuipmentInfo), ref b_Flag, ref msg);
                    if (obj is EuipmentInfo)
                    {
                        string typecode = string.Empty;

                        EuipmentInfo euipmentInfo = obj as EuipmentInfo;
                        typecode = euipmentInfo.Msg_Method;
                        List<ResultParam> resultParams = new List<ResultParam>();
                        ResultParam resultParam = new ResultParam();
                        if (typecode == "EuipmentStatus")
                        {
                            foreach (EquipmentParam equipmentParam in euipmentInfo.Msg_Params)
                            {
                                
                                //更新设备状态 
                                resultParam.DeviceCode = equipmentParam.DeviceCode;
                                resultParam.DeviceType = equipmentParam.DeviceType;
                                resultParam.Code = "0";
                                resultParams.Add(resultParam);
                                if (int.Parse(equipmentParam.AlarmCode) > 0)
                                {
                                    WriteLog(rtb_msg, resultParam.DeviceType + resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));
                                    QueueSpeech.AddQueue(resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));
                                }
                            }
                            byte[] byt = new byte[1000];
                            string sendInfo = JsonConvert.SerializeObject(resultParams);
                            byte[] infotemp = System.Text.ASCIIEncoding.Default.GetBytes(sendInfo);
                            Array.Copy(infotemp, 0, byt, 0, infotemp.Length);
                            ocv2server.SendMessage(byt);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(rtb_msg, ex.Message + ex.StackTrace + ex.Source + ex.TargetSite);
            }
        }

        private void ocv3_Notify(string Command, object mesg)
        {
            bool b_Flag = false;
            string msg = "";
            try
            {
                if (Command == "Heart")
                {
                    OCV3.BackColor = OCV3.BackColor == Color.Lime ? Color.LimeGreen : Color.Lime;
                    OCV3.Text = "OCV3号机:已连接";
                }
                else if (Command == "Connect")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    OCV3.BackColor = Color.Lime;
                }
                else if (Command == "Break")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    OCV3.BackColor = Color.RosyBrown;
                }
                else if (Command == "Listen")
                {
                    WriteLog(rtb_conn, " OCV3号机开启监听！" + mesg);
                    OCV3.BackColor = Color.Orange;
                    OCV3.Text = "OCV3号机:监听中";
                }
                else if (Command == "Listen1")
                {
                    OCV3.BackColor = Color.Orange;
                    OCV3.Text = "OCV3号机:监听中";
                }
                else
                {
                    CommonHelper helper = new CommonHelper();

                    object obj = helper.Deserialize(mesg.ToString(), typeof(EuipmentInfo), ref b_Flag, ref msg);
                    if (obj is EuipmentInfo)
                    {
                        string typecode = string.Empty;

                        EuipmentInfo euipmentInfo = obj as EuipmentInfo;
                        typecode = euipmentInfo.Msg_Method;
                        List<ResultParam> resultParams = new List<ResultParam>();
                        ResultParam resultParam = new ResultParam();
                        if (typecode == "EuipmentStatus")
                        {
                            foreach (EquipmentParam equipmentParam in euipmentInfo.Msg_Params)
                            {
                                //更新设备状态 
                                resultParam.DeviceCode = equipmentParam.DeviceCode;
                                resultParam.DeviceType = equipmentParam.DeviceType;
                                resultParam.Code = "0";
                                resultParams.Add(resultParam);
                                if (int.Parse(equipmentParam.AlarmCode) > 0)
                                {
                                    WriteLog(rtb_msg, resultParam.DeviceType + resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));
                                    QueueSpeech.AddQueue(resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));
                                }
                            }
                            byte[] byt = new byte[1000];
                            string sendInfo = JsonConvert.SerializeObject(resultParams);
                            byte[] infotemp = System.Text.ASCIIEncoding.Default.GetBytes(sendInfo);
                            Array.Copy(infotemp, 0, byt, 0, infotemp.Length);
                            ocv3server.SendMessage(byt);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(rtb_msg, ex.Message + ex.StackTrace + ex.Source + ex.TargetSite);
            }
        }

        private void dcir1_Notify(string Command, object mesg)
        {
            bool b_Flag = false;
            string msg = "";
            try
            {
                if (Command == "Heart")
                {
                    DCIR1.BackColor = DCIR1.BackColor == Color.Lime ? Color.LimeGreen : Color.Lime;
                    DCIR1.Text = "DCIR1号机:已连接";
                }
                else if (Command == "Connect")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    DCIR1.BackColor = Color.Lime;
                }
                else if (Command == "Break")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    DCIR1.BackColor = Color.RosyBrown;
                }
                else if (Command == "Listen")
                {
                    WriteLog(rtb_conn, " DCIR1号机开启监听！" + mesg);
                    DCIR1.BackColor = Color.Orange;
                    DCIR1.Text = "DCIR1号机:监听中";
                }
                else if (Command == "Listen1")
                {
                    DCIR1.BackColor = Color.Orange;
                    DCIR1.Text = "DCIR1号机:监听中";
                }
                else
                {
                    CommonHelper helper = new CommonHelper();

                    object obj = helper.Deserialize(mesg.ToString(), typeof(EuipmentInfo), ref b_Flag, ref msg);
                    if (obj is EuipmentInfo)
                    {
                        string typecode = string.Empty;

                        EuipmentInfo euipmentInfo = obj as EuipmentInfo;
                        typecode = euipmentInfo.Msg_Method;
                        List<ResultParam> resultParams = new List<ResultParam>();
                        ResultParam resultParam = new ResultParam();
                        if (typecode == "EuipmentStatus")
                        {
                            foreach (EquipmentParam equipmentParam in euipmentInfo.Msg_Params)
                            {
                                //更新设备状态 
                                resultParam.DeviceCode = equipmentParam.DeviceCode;
                                resultParam.DeviceType = equipmentParam.DeviceType;
                                resultParam.Code = "0";
                                resultParams.Add(resultParam);
                                if (int.Parse(equipmentParam.AlarmCode) > 0)
                                {
                                    WriteLog(rtb_msg, resultParam.DeviceType + resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));
                                }
                            }
                            byte[] byt = new byte[1000];
                            string sendInfo = JsonConvert.SerializeObject(resultParams);
                            byte[] infotemp = System.Text.ASCIIEncoding.Default.GetBytes(sendInfo);
                            Array.Copy(infotemp, 0, byt, 0, infotemp.Length);
                            dcir1server.SendMessage(byt);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(rtb_msg, ex.Message + ex.StackTrace + ex.Source + ex.TargetSite);
            }
        }
        private void dcir2_Notify(string Command, object mesg)
        {
            bool b_Flag = false;
            string msg = "";
            try
            {
                if (Command == "Heart")
                {
                    DCIR2.BackColor = DCIR2.BackColor == Color.Lime ? Color.LimeGreen : Color.Lime;
                    DCIR2.Text = "DCIR2号机:已连接";
                }
                else if (Command == "Connect")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    DCIR2.BackColor = Color.Lime;
                }
                else if (Command == "Break")
                {
                    WriteLog(rtb_msg, "" + mesg);
                    DCIR2.BackColor = Color.RosyBrown;
                }
                else if (Command == "Listen")
                {
                    WriteLog(rtb_conn, " DCIR2号机开启监听！" + mesg);
                    DCIR2.BackColor = Color.Orange;
                    DCIR2.Text = "DCIR2号机:监听中";
                }
                else if (Command == "Listen1")
                {
                    DCIR2.BackColor = Color.Orange;
                    DCIR2.Text = "DCIR2号机:监听中";
                }
                else
                {
                    CommonHelper helper = new CommonHelper();

                    object obj = helper.Deserialize(mesg.ToString(), typeof(EuipmentInfo), ref b_Flag, ref msg);
                    if (obj is EuipmentInfo)
                    {
                        string typecode = string.Empty;

                        EuipmentInfo euipmentInfo = obj as EuipmentInfo;
                        typecode = euipmentInfo.Msg_Method;
                        List<ResultParam> resultParams = new List<ResultParam>();
                        ResultParam resultParam = new ResultParam();
                        if (typecode == "EuipmentStatus")
                        {
                            foreach (EquipmentParam equipmentParam in euipmentInfo.Msg_Params)
                            {
                                //更新设备状态 
                                resultParam.DeviceCode = equipmentParam.DeviceCode;
                                resultParam.DeviceType = equipmentParam.DeviceType;
                                resultParam.Code = "0";
                                resultParams.Add(resultParam);
                                if (int.Parse(equipmentParam.AlarmCode) > 0)
                                {
                                    WriteLog(rtb_msg, resultParam.DeviceType + resultParam.DeviceCode + "故障.故障原因:" + getAlarm(equipmentParam.AlarmCode));
                                }
                            }
                            byte[] byt = new byte[1000];
                            string sendInfo = JsonConvert.SerializeObject(resultParams);
                            byte[] infotemp = System.Text.ASCIIEncoding.Default.GetBytes(sendInfo);
                            Array.Copy(infotemp, 0, byt, 0, infotemp.Length);
                            dcir2server.SendMessage(byt);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(rtb_msg, ex.Message + ex.StackTrace + ex.Source + ex.TargetSite);
            }
        }

        private string getAlarm(string alarmCode)
        {
            string alarmInfo = "未知故障";
            if (File.Exists(".\\OCVAlarm.txt"))
            {
                FileStream fs = new FileStream(".\\OCVAlarm.txt", FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string strline = sr.ReadToEnd().Replace("\r", "").Replace("\n", "");
                string[] msg = strline.Split(new char[] { ';' });

                foreach (var msg1 in msg)
                {
                    if (alarmCode == msg1.Split(',')[0])
                    {
                        alarmInfo = msg1.Split(',')[1];
                        break;
                    }
                }
            }
            return alarmInfo;
        }
        private void WriteLog(RichTextBox rtb, String msg)
        {
            if (!msg.Contains("开始监听！！"))
            {
                log.WriteLog(System.DateTime.Now.ToString("yyyyMMdd") + "OCV与DCIR日志", msg);
            }
            if (rtb != null)
                ShowText(rtb, msg);
        }

        private void ShowText(RichTextBox rb, string msg)
        {
            if (rb.InvokeRequired)
            {
                RichBoxCallBack rbcb = new RichBoxCallBack(ShowText);
                this.Invoke(rbcb, new object[] { rb, msg });
            }
            else
            {
                if (rb.TextLength > 10000)
                    rb.Clear();
                if (msg.Contains("失败") || msg.Contains("故障"))
                    rb.SelectionColor = Color.Red;
                else
                    rb.SelectionColor = Color.Black;
                if (!string.IsNullOrEmpty(msg))
                    rb.AppendText(System.DateTime.Now.ToString() + ": " + msg + "\n");
            }
        }
    }
}

